package com.yuhong.springbootinit.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yuhong.springbootinit.mapper.ProfileMapper;
import com.yuhong.springbootinit.model.dto.profile.PredictRequest;
import com.yuhong.springbootinit.model.entity.Interview;
import com.yuhong.springbootinit.model.entity.Profile;
import com.yuhong.springbootinit.service.ProfileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @BelongsProject: resume-analysis-system
 * @BelongsPackage: com.yuhong.springbootinit.controller
 * @Author: renyuhong
 * @CreateTime: 2025-05-05  10:23
 * @Description:
 * @Version: 1.0
 */
@RestController
@RequestMapping("/model")
@Slf4j
public class ModelController {

    @Resource
    private ProfileService profileService;

    @Resource
    private ProfileMapper profileMapper;

    @PostMapping("/predict")
    public ResponseEntity<List<Double>> runPredict(@RequestBody PredictRequest predictRequest) {

        String positionId = predictRequest.getPositionId();
        Integer rate = predictRequest.getRate();

        List<String> profileIds = profileService.batchSelection(positionId);
        int count = profileIds.size();

        List<Double> resultList = new ArrayList<>();
        try {
            // 构造命令（使用 conda run 指定环境）
            List<String> command = new ArrayList<>();
            command.add("C:\\Users\\10467\\miniconda3\\envs\\python39\\python.exe");

//            command.add("conda");
//            command.add("run");
//            command.add("-n");
//            command.add("python39");
//            command.add("python");
            command.add("predict.py");
            command.add("../data/test.txt");
            command.add("--profile_num");
            command.add(String.valueOf(count));

            ProcessBuilder processBuilder = new ProcessBuilder(command);
            processBuilder.directory(new File("E:/代码/deepLearning/PyProject/ProfileSelection/deepcrossing")); // 设置工作目录
            processBuilder.redirectErrorStream(true); // 合并错误输出

            Process process = processBuilder.start();

            // 获取输出流并提取预测值
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
                boolean capture = false;
                String line;
                while ((line = reader.readLine()) != null) {
                    if (line.contains("Top predict results:")) {
                        capture = true;
                        continue;
                    }
                    if (capture) {
                        // 提取预测值
                        line = line.replaceAll("[\\[\\]]", "").trim();
                        if (!line.isEmpty()) {
                            String[] values = line.split("\\s+");
                            for (String val : values) {
                                try {
                                    resultList.add(Double.parseDouble(val));
                                } catch (NumberFormatException ignored) {}
                            }
                        }
                    }
                }
            }

            int exitCode = process.waitFor();
            if (exitCode != 0) {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
            }

            //resultList 的结果插入对应个人信息中
            resultList.sort(Comparator.reverseOrder());

            for (int i = 0; i < profileIds.size(); i++) {
                String profileId = profileIds.get(i);
                double level = resultList.get(i);

                profileMapper.update(
                        null,
                        new LambdaUpdateWrapper<Profile>()
                                .eq(Profile::getProfileId, profileId)
                                .set(Profile::getLevel, level)
                );
            }


            return ResponseEntity.ok(resultList);

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

}
